package com.pandora.credit.web.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.pandora.credit.enums.ExceptionEnum.*;
import static com.pandora.credit.web.advice.util.ExceptionEnumConverter.convertToMap;

/**
 * @author developer
 */
@RestController
public class ErrorController {

    private static final String ERROR_THROWN = "javax.servlet.error.exception";
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private void printInternalException(HttpServletRequest request) {
        Throwable throwable = (Throwable) request.getAttribute(ERROR_THROWN);
        if (throwable != null) {
            logger.error("tomcat internal error", throwable);
        }
    }

    @RequestMapping(value = "/error_400", produces = "application/json;charset=UTF-8")
    public Map<String, Object> error400(HttpServletRequest request) {
        printInternalException(request);
        return convertToMap(BadRequest);
    }

    @RequestMapping(value = "/error_404", produces = "application/json;charset=UTF-8")
    public Map<String, Object> error404(HttpServletRequest request) {
        printInternalException(request);
        return convertToMap(NotFoundError);
    }

    @RequestMapping(value = "/error_405", produces = "application/json;charset=UTF-8")
    public Map<String, Object> error405(HttpServletRequest request) {
        printInternalException(request);
        return convertToMap(NotSupportError);
    }

    @RequestMapping(value = "/error_500", produces = "application/json;charset=UTF-8")
    public Map<String, Object> error500(HttpServletRequest request) {
        printInternalException(request);
        return convertToMap(InternalServerError);
    }
}
